﻿//=====================================================
// Copyright © 2017-2018 xuxuzhaozhao
// All rights reserved
// GUID: bf45ea56-8947-455d-981d-ab9eae85d7dd
// CLR版本: 4.0.30319.42000
// 命名空间名称: xuxuzhaozhao.Blog.Application
// 文件名: XuUserAppService
// 当前系统时间: 2017/11/6 17:34:26
// 当前登录用户名: xuxuzhaozhao
//======================================================

using System.Linq;
using System.Web.Security;
using xuxuzhaozhao.Blog.Application.XuUser.Dto;
using xuxuzhaozhao.Blog.Infrastructure.XuEntityFramework;
using xuxuzhaozhao.Blog.Infrastructure.XuTools;

namespace xuxuzhaozhao.Blog.Application.XuUserService
{
    public interface IXuUserAppService 
    {
        object Register(XuUserRegisterInput input);
        object Login(XuUserLoginInput input);
        object GetResetPassword();
    }
    public class XuUserAppService :  IXuUserAppService
    {
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public object Register(XuUserRegisterInput input)
        {
            var result = new XuResult();
            using (var db = new XuxuzhaozhaoDbContext())
            {
                if (db.XuUser.Any(t => t.UserName == input.UserName))
                {
                    result.Message = "数据库已有此账号名，请换一个重试。";
                    result.Code = StatusCode.Fail;
                    return result;
                }
                var user = new Domain.XuUser()
                {
                    Phone = input.Phone,
                    Password = input.Password,
                    UserName = input.UserName,
                    RealName = input.RealName
                };
                db.XuUser.Add(user);
                if (db.SaveChanges() > 0)
                    return result.Success();
            }
            return result.Fail();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public object Login(XuUserLoginInput input)
        {
            var result = new XuResult();
            if (HandLogin(input))
            {
                FormsAuthentication.SetAuthCookie(input.UserName, false);
                return result.Success();
            }
            return result.Fail();
        }

        private bool HandLogin(XuUserLoginInput input)
        {
            using (var db = new XuxuzhaozhaoDbContext())
            {
                return db.XuUser.Any(t => t.UserName == input.UserName && t.Password == input.Password);
            }
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <returns></returns>
        public object GetResetPassword()
        {
            throw new System.NotImplementedException();
        }
    }
}
